/*
 * @Description: 全宗上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2022-01-27 18:20:29
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import {
  ADD_LEVEL_BY_ID,
  ARC_TYPE_LOADING,
  METADATA_LOADING,
  METADATA_LOADING_FINISH,
  SET_ARC_TYPE_LIST,
  SET_METADATA_LIST
} from '../constants';
import { MetadataConfigReducer } from '../reducers/MetadataConfigReducer';
import { fetchArchiveTypeList, fetchTableField } from '@/api/system';
import { fetchLevelByATId } from '@/api/archivesType';

const initialState = {
  ATList: [],
  metadataLoading: false,
  metadataList: []
};

const MetadataConfigContext = createContext();

const MetadataConfigContextProvider = (props) => {
  const [state, dispatch] = useReducer(MetadataConfigReducer, initialState);

  const actions = {
    async fetchArcList() {
      dispatch({ type: ARC_TYPE_LOADING });
      const res = await fetchArchiveTypeList();
      const { data } = res;
      dispatch({ type: SET_ARC_TYPE_LIST, data });
    },

    async fetchATLevel(id, resolve) {
      const res = await fetchLevelByATId(id);
      const { data } = res;
      dispatch({ type: ADD_LEVEL_BY_ID, id, data });
      resolve();
    },

    async fetchMateData(tableName) {
      dispatch({ type: METADATA_LOADING });
      // const res = await fetchTableField(tableName);
      // const data = res.data;
      // dispatch({ type: SET_METADATA_LIST, data });
      fetchTableField(tableName)
        .then((res) => {
          const { data } = res;
          dispatch({ type: SET_METADATA_LIST, data });
        })
        .catch((err) => {
          console.log(err);
          dispatch({ type: SET_METADATA_LIST, data: [] });
        })
        .finally(() => {
          dispatch({ type: METADATA_LOADING_FINISH });
        });
    }
  };

  useEffect(() => {
    actions.fetchArcList();
  }, []);

  return (
    <MetadataConfigContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </MetadataConfigContext.Provider>
  );
};

export const useMetadataContext = () => {
  return useContext(MetadataConfigContext);
};

export { MetadataConfigContext, MetadataConfigContextProvider };
